package com.imut.oa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imut.oa.common.ErrorCode;
import com.imut.oa.contant.JwtProperties;
import com.imut.oa.exception.BusinessException;
import com.imut.oa.mapper.UserMapper;
import com.imut.oa.pojo.dto.AdminUpdateDTO;
import com.imut.oa.pojo.entity.Departments;
import com.imut.oa.pojo.entity.User;
import com.imut.oa.service.UserService;
import com.imut.oa.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.imut.oa.config.CaptureConfiguration.CAPTCHA_MAP;
import static com.imut.oa.contant.UserContant.USER_LOGIN_STATE;

/**
* @author YRX
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-11-25 16:22:49
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    @Resource
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        //验证是否非空，不为空执行下一步
        if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR,"参数为空");
            //账号不能小于4位
        }
        if (userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号小于4位");
        }
        if (userAccount.length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号大于16位");
        }
        //密码不能小于8位
        if (userPassword.length()<8 || checkPassword.length()<8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码小于8位");
        }
        if (userPassword.length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码大于16位");
        }
        //账号不能重复
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userAccount",userAccount);
        long count = userMapper.selectCount(qw);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号重复");
        }
        //账号不包含特殊字符
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（） ——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }
        //密码和校验密码不同
        if(!(userPassword.equals(checkPassword))){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码和校验密码不同");
        }
        //        3.对密码进行加密

        String encryptPassword = DigestUtils.md5DigestAsHex((USER_LOGIN_STATE + userPassword).getBytes());
//        4.向数据库插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        boolean save = this.save(user);
        if (!save){
            throw new BusinessException(ErrorCode.FAIL_SEARCH,"注册失败");
        }
        return user.getId();
    }

    @Override
    public String userLogin(@RequestParam String key, String userAccount, String userPassword, String code, HttpServletRequest request) {
        //验证是否非空，不为空执行下一步
        if (StringUtils.isAnyBlank(userAccount,userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号密码为空");
            //账号不能小于4位
        }
        if (userAccount.length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能小于4位");
        }
        if (userAccount.length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号大于16位");
        }
        //密码不能小于8位
        if (userPassword.length()<8 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能小于8位");
        }
        if (userPassword.length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码大于16位");
        }
        if (!code.equals(CAPTCHA_MAP.get(key))){
            CAPTCHA_MAP.remove(key);
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"验证码错误");
        }
        //账户不包含特殊字符
        String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（） ——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(regEx).matcher(userAccount);
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号包含特殊字符");
        }
        //加密
    //    String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("userAccount",userAccount);
        User user = userMapper.selectOne(qw);
        //用户不存在
        if(user ==null){
            log.info(" user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.FAIL_SEARCH,"用户不存在");
        }
        //对用户传来的信息加密,如果与数据库中密码不一样，则返回错误信息
        if(!DigestUtils.md5DigestAsHex((USER_LOGIN_STATE + userPassword).getBytes()).equals(user.getUserPassword())){
            System.out.println(DigestUtils.md5DigestAsHex((USER_LOGIN_STATE + userPassword).getBytes()).equals(user.getUserPassword()));
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不正确");
        }
        //记录用户态
     //   request.getSession().setAttribute(USER_LOGIN_STATE,user);
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id",user.getId());
        claims.put("userAccount",user.getUserAccount());
        String token = JwtUtil.genToken(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),claims
        );

        //脱敏
        return token;
    }
    @Override
    public User getSafetyUser(User originUser){
        if(originUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"脱敏失败");
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUserName(originUser.getUserName());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setRole(originUser.getRole());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        return safetyUser;
    }
    @Transactional
    @Override
    public void updateAdminInfo(AdminUpdateDTO adminUpdateDTO) {
        if (adminUpdateDTO.getUserAccount().length()<4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号不能小于4位");
        }
        if (adminUpdateDTO.getUserAccount().length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号大于16位");
        }
        if (adminUpdateDTO.getUserName().length()>16){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名大于16位");
        }
        if (adminUpdateDTO.getPhone().length() != 11){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"手机号是11位");
        }
        if (adminUpdateDTO.getGender() != 0 && adminUpdateDTO.getGender() != 1){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"性别只能是0或1");
        }
        //邮箱校验
        String emailRegEx = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
        Pattern pattern = Pattern.compile(emailRegEx);
        Matcher matcher = pattern.matcher(adminUpdateDTO.getEmail());
        if (!matcher.matches()) { // 注意这里用 matches() 而不是 find()
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        }

        adminUpdateDTO.setUpdateTime(LocalDateTime.now());
        User user = new User();
        BeanUtils.copyProperties(adminUpdateDTO,user);
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(User user) {
        userMapper.update(user);
    }

    @Override
    public void updatePassword(Long currentId, String oldPwd, String newPwd, String rePwd) {
        String userPasswordById = userMapper.getUserPasswordById(currentId);
        if (oldPwd.equals(newPwd)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"新旧密码不能相同");
        }
        if (newPwd.length()<8 ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码不能小于8位");
        }
        if (!newPwd.equals(rePwd)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"两次密码不一致");
        }
        if (!DigestUtils.md5DigestAsHex((USER_LOGIN_STATE + oldPwd).getBytes()).equals(userPasswordById)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"旧密码错误");
        }
        User user = new User();
        user.setId(currentId);
        user.setUserPassword(DigestUtils.md5DigestAsHex((USER_LOGIN_STATE + newPwd).getBytes()));
        userMapper.update(user);
    }


}




